# encoding=utf-8

import smtplib
from email.mime.text import MIMEText
import sys
import os

PATH = "D:\out.txt"


def send_email(user, pwd, recipient, subject, body):
    FROM = user
    # TO = recipient if type(recipient) is list else [recipient]

    msg = MIMEText(body.encode('utf-8'), _charset='utf-8')
    msg['Subject'] = subject
    msg['From'] = user
    msg['To'] = recipient

    # Prepare actual message
    # message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    # """ % (FROM, ", ".join(TO), subject, body)
    try:
        server_ssl = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
        server_ssl.ehlo()  # optional, called by login()
        server_ssl.login(user, pwd)
        # ssl server doesn't support or need tls, so don't call server_ssl.starttls()
        server_ssl.sendmail(FROM, [recipient], msg.as_string())
        # server_ssl.quit()
        server_ssl.close()
        print('successfully sent the mail')
    except Exception as e:
        print("failed to send mail")
        print(e)


def dispose_commit(repository, revision):
    author = os.popen("svnlook author " + repository + " -r " + revision).read().strip()
    msg = os.popen("svnlook log " + repository + " -r " + revision).read().strip()
    files = os.popen("svnlook changed " + repository + " -r " + revision).read().strip()
    if os.path.exists(PATH):
        f = open(PATH, "a")
        f.writelines("\n")
        f.writelines("------")
        f.writelines("\n")
    else:
        f = open(PATH, "w")
    if "yangming" == author:
        f.writelines("repository : " + repository + "\n")
        f.writelines("revision : " + revision + "\n")
        f.writelines("author : " + author + "\n")
        f.writelines("msg : " + msg + "\n")
        f.writelines("changed :\n" + files)
        f.close()

        # subject = ''.join(["Review申请，", author, "提交了代码，更新内容：", msg])
        # body = ''.join(["From ", author, "\n",
        #                 "您好 ", "代码有新的提交，请及时Review", "\n",
        #                 "更新内容：", msg, "\n",
        #                 "---", "\n",
        #                 files])
        # send_email("ming.yang@yidatec.com", "!QAZ2wsx", "ming.yang@yidatec.com", subject, body)


if __name__ == '__main__':
    # send_email("ming.yang@yidatec.com", "!QAZ2wsx", "ming.yang@yidatec.com", "hello", "Hello!!!")

    print('Number of arguments:', len(sys.argv), 'arguments.')
    print('Argument List:', str(sys.argv))
    REPOS = str(sys.argv[1])
    TXN = str(sys.argv[2])
    dispose_commit(REPOS, TXN)
